﻿using System;
using Newtonsoft.Json;
using StackExchange.Redis;

namespace Shop.Tools.Util
{
    /// <summary>
    /// Redis帮助类型
    /// </summary>
    public static class RedisHelper
    {
        private static ConnectionMultiplexer redis => ConnectionMultiplexer.Connect(StaticConst.RedisConfig);
        private static IDatabase db => redis.GetDatabase();

        /// <summary>
        /// 添加 值
        /// </summary>
        /// <typeparam name="T">类型</typeparam>
        /// <param name="key">key</param>
        /// <param name="value">值</param>
        /// <returns></returns>
        public static bool SetValue<T>(string key, T value)
        {
            try
            {
                var json = JsonConvert.SerializeObject(value);
                return db.StringSet(key, json);
            }
            catch (Exception e)
            {
                return false;
            }

        }

        /// <summary>
        /// 添加【需传入过期时长】 值
        /// </summary>
        /// <typeparam name="T">类型</typeparam>
        /// <param name="key">key</param>
        /// <param name="value">值</param>
        /// <param name="expiry">过期时长</param>
        /// <returns></returns>
        public static bool SetValue<T>(string key, T value, TimeSpan expiry)
        {
            try
            {
                var json = JsonConvert.SerializeObject(value);
                return db.StringSet(key, json, expiry);
            }
            catch (Exception e)
            {
                return false;
            }

        }

        /// <summary>
        /// 根据 Key 获取
        /// </summary>
        /// <typeparam name="T">类型</typeparam>
        /// <param name="key">传入Key</param>
        /// <returns>T</returns>
        public static T GetValue<T>(string key)
        {
            try
            {
                var json = db.StringGet(key);
                return JsonConvert.DeserializeObject<T>(json);
            }
            catch (Exception e)
            {
                return default(T);
            }
        }

        /// <summary>
        /// 根据Key 删除
        /// </summary>
        /// <param name="key">传入Key</param>
        /// <returns></returns>
        public static bool KeyDelete(string key)
        {
            try
            {
                return db.KeyDelete(key);
            }
            catch (Exception e)
            {
                return false;
            }

        }
    }
}